package com.gliese.bambook.service.snb.impl;

import java.io.File;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.gliese.bambook.object.Snbc;
import com.gliese.bambook.service.snb.interfaces.UpdateSnbfService;
import com.gliese.bambook.util.SnbUtils;

public class BambookUpdateSnbfService implements UpdateSnbfService {
	private Log log = LogFactory.getLog(BambookUpdateSnbfService.class);

	@Override
	public void updateTocSnbf(Snbc snbc, String snbcFileName, int index) {
		String absPathOfTocSnbf = SnbUtils.getSnbTodayAbsPath(snbc) + "snbf"
				+ System.getProperty("file.separator") + "toc.snbf";
		File tocSnbfFile = new File(absPathOfTocSnbf);
		if (!tocSnbfFile.exists()) {
			try {
				tocSnbfFile.createNewFile();
			} catch (IOException e) {
				log.error("can not create File " + absPathOfTocSnbf);
				System.exit(0);
			}
			prepareTocSnbf(tocSnbfFile);
		}
		SAXReader saxReader = new SAXReader();
		try {
			Document doc = saxReader.read(tocSnbfFile);
			// chapters ++1
			Element chapters = (Element) doc
					.selectSingleNode("/toc-snbf/head/chapters");
			Integer chapterNum = Integer.parseInt(chapters.getTextTrim()) + 1;
			chapters.setText(chapterNum.toString());

			// add chapter to body
			Element body = (Element) doc.selectSingleNode("/toc-snbf/body");
			Element addedChapter = body.addElement("chapter");
			addedChapter.addAttribute("src", snbcFileName);
			addedChapter.addCDATA("Article " + index + ":   "
					+ snbc.getSnbcTitle());
			SnbUtils.wirteDocument(doc, absPathOfTocSnbf);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}

	}

	/**
	 * prepare toc.snbc
	 * 
	 * @param file
	 */
	private void prepareTocSnbf(File file) {
		SAXReader saxReader = new SAXReader();
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("toc-snbf");
		Element head = root.addElement("head");
		Element chapters = head.addElement("chapters");
		chapters.addText("0");
		root.addElement("body");
		SnbUtils.wirteDocument(doc, file.getAbsolutePath());

	}
}
